package mail

import (
	"github.com/go-gomail/gomail"
	"log"
)

var ChanMail = make(chan *SendEmailParam, 1000)

func InitEmail(ep *ServerParam) (m *gomail.Dialer) {
	m = gomail.NewDialer(ep.ServerHost, ep.ServerPort, ep.UserName, ep.Password)
	return
}


func SendEmail(sep *SendEmailParam){
	m := InitEmail(&sep.Server)
	msg :=  gomail.NewMessage()
	if len(sep.ToUsers) < 1{
		return
	}
	msg.SetHeader("To", sep.ToUsers...)
	if len(sep.CCUsers) > 0{
		msg.SetHeader("Cc", sep.CCUsers...)
	}

	msg.SetAddressHeader("From", sep.Server.UserName, sep.Server.AliasName)
	msg.SetHeader("Subject", sep.Subject)
	msg.SetBody("text/html", sep.HTMLBody)
	err := m.DialAndSend(msg)
	if err != nil {
		log.Print(err.Error())
	}
}

func GoSend(){
	for ; ;  {
		info := <-ChanMail
		SendEmail(info)
	}
}
